﻿using System.Collections.ObjectModel;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using WpfApp1.Services;

namespace WpfApp1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private SocketServerManager? _serverManager;
        private readonly ObservableCollection<ClientInfo> _clientList = new();
        private int _totalMessageCount = 0;

        public MainWindow()
        {
            InitializeComponent();
            InitializeServer();
            
            // 绑定客户端列表
            lvClients.ItemsSource = _clientList;
        }

        /// <summary>
        /// 初始化服务器
        /// </summary>
        private void InitializeServer()
        {
            var config = new SocketServerConfig
            {
                ListenAddress = txtListenAddress.Text,
                ListenPort = int.Parse(txtListenPort.Text),
                MaxConnections = 100,
                BufferSize = 1024
            };

            _serverManager = new SocketServerManager(config);

            // 订阅事件
            _serverManager.ServerStateChanged += OnServerStateChanged;
            _serverManager.ClientConnectionChanged += OnClientConnectionChanged;
            _serverManager.MessageReceived += OnMessageReceived;
            _serverManager.LogMessage += OnLogMessage;

            AddLogMessage("服务器初始化完成");
        }

        /// <summary>
        /// 启动服务器
        /// </summary>
        private async void StartServer_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 更新配置
                var config = new SocketServerConfig
                {
                    ListenAddress = txtListenAddress.Text,
                    ListenPort = int.Parse(txtListenPort.Text)
                };

                _serverManager = new SocketServerManager(config);
                _serverManager.ServerStateChanged += OnServerStateChanged;
                _serverManager.ClientConnectionChanged += OnClientConnectionChanged;
                _serverManager.MessageReceived += OnMessageReceived;
                _serverManager.LogMessage += OnLogMessage;

                bool success = await _serverManager.StartAsync();
                if (success)
                {
                    btnStartServer.IsEnabled = false;
                    btnStopServer.IsEnabled = true;
                    txtListenAddress.IsEnabled = false;
                    txtListenPort.IsEnabled = false;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"启动服务器失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 停止服务器
        /// </summary>
        private void StopServer_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                _serverManager?.Stop();
                btnStartServer.IsEnabled = true;
                btnStopServer.IsEnabled = false;
                txtListenAddress.IsEnabled = true;
                txtListenPort.IsEnabled = true;
                
                _clientList.Clear();
                _totalMessageCount = 0;
                UpdateStats();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"停止服务器失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 清空日志
        /// </summary>
        private void ClearLog_Click(object sender, RoutedEventArgs e)
        {
            txtLog.Clear();
        }

        /// <summary>
        /// 发送消息给选中的客户端
        /// </summary>
        private async void SendToSelected_Click(object sender, RoutedEventArgs e)
        {
            if (lvClients.SelectedItem is ClientInfo selectedClient && _serverManager != null)
            {
                string message = txtMessage.Text;
                if (!string.IsNullOrWhiteSpace(message))
                {
                    await _serverManager.SendToClientAsync(selectedClient.Id, message);
                }
            }
            else
            {
                MessageBox.Show("请选择一个客户端", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }

        /// <summary>
        /// 广播消息给所有客户端
        /// </summary>
        private async void Broadcast_Click(object sender, RoutedEventArgs e)
        {
            if (_serverManager != null)
            {
                string message = txtMessage.Text;
                if (!string.IsNullOrWhiteSpace(message))
                {
                    await _serverManager.BroadcastAsync(message);
                }
            }
        }

        /// <summary>
        /// 客户端列表点击事件
        /// </summary>
        private void ClientListView_Click(object sender, RoutedEventArgs e)
        {
            // 可以在这里处理列表头点击排序等操作
        }

        #region 事件处理方法

        /// <summary>
        /// 服务器状态变化事件
        /// </summary>
        private void OnServerStateChanged(bool isListening)
        {
            Dispatcher.Invoke(() =>
            {
                lblServerStatus.Text = isListening ? "运行中" : "已停止";
                lblServerStatus.Foreground = isListening ? Brushes.Green : Brushes.Red;
                UpdateStats();
            });
        }

        /// <summary>
        /// 客户端连接状态变化事件
        /// </summary>
        private void OnClientConnectionChanged(ClientInfo client, bool connected)
        {
            Dispatcher.Invoke(() =>
            {
                if (connected)
                {
                    _clientList.Add(client);
                }
                else
                {
                    var existingClient = _clientList.FirstOrDefault(c => c.Id == client.Id);
                    if (existingClient != null)
                    {
                        _clientList.Remove(existingClient);
                    }
                }
                UpdateStats();
            });
        }

        /// <summary>
        /// 消息接收事件
        /// </summary>
        private void OnMessageReceived(ClientInfo client, string message)
        {
            Dispatcher.Invoke(() =>
            {
                _totalMessageCount++;
                
                // 更新客户端列表中的消息计数
                var clientInList = _clientList.FirstOrDefault(c => c.Id == client.Id);
                if (clientInList != null)
                {
                    var index = _clientList.IndexOf(clientInList);
                    _clientList[index] = client; // 触发UI更新
                }
                
                UpdateStats();
            });
        }

        /// <summary>
        /// 日志消息事件
        /// </summary>
        private void OnLogMessage(string message)
        {
            Dispatcher.Invoke(() =>
            {
                AddLogMessage(message);
            });
        }

        /// <summary>
        /// 添加日志消息
        /// </summary>
        private void AddLogMessage(string message)
        {
            string timestamp = DateTime.Now.ToString("HH:mm:ss");
            txtLog.AppendText($"[{timestamp}] {message}\n");
            
            // 自动滚动到底部
            txtLog.ScrollToEnd();
            
            // 限制日志长度
            if (txtLog.LineCount > 1000)
            {
                var lines = txtLog.Text.Split('\n');
                txtLog.Text = string.Join("\n", lines.Skip(100));
            }
        }

        /// <summary>
        /// 更新统计信息
        /// </summary>
        private void UpdateStats()
        {
            lblClientCount.Text = _clientList.Count.ToString();
            lblMessageCount.Text = _totalMessageCount.ToString();
        }

        #endregion

        /// <summary>
        /// 窗口关闭事件
        /// </summary>
        protected override void OnClosed(EventArgs e)
        {
            try
            {
                _serverManager?.Stop();
            }
            catch (Exception ex)
            {
                // 记录错误但不阻止关闭
                System.Diagnostics.Debug.WriteLine($"关闭窗口时停止服务器出错: {ex.Message}");
            }
            
            base.OnClosed(e);
        }
    }
}